<template>
	<view class="message-detail-page">
		<!-- 聊天头部 -->
		<view class="message-detail-page__header">
			<text class="message-detail-page__header-name">{{ chatPartnerName }}</text>
		</view>
		
		<!-- 聊天消息列表 -->
		<scroll-view 
			class="message-detail-page__messages" 
			scroll-y 
			:scroll-top="scrollTop" 
			scroll-with-animation
			@scrolltolower="handleScrollToBottom">
			<view 
				class="message-detail-page__item" 
				v-for="(message, index) in messageList" 
				:key="message.id || index"
				:class="{ 'message-detail-page__item--self': message.isSelf }">
				<!-- 对方消息（左侧） -->
				<template v-if="!message.isSelf">
					<view class="message-detail-page__avatar">
						<text class="message-detail-page__avatar-text">{{ getAvatarText(message.senderName) }}</text>
					</view>
					<view class="message-detail-page__bubble message-detail-page__bubble--other">
						<!-- <text class="message-detail-page__bubble-name">{{ message.senderName }}</text> -->
						<text class="message-detail-page__bubble-text">{{ message.content }}</text>
						<text class="message-detail-page__bubble-time">{{ formatTime(message.timestamp) }}</text>
					</view>
				</template>
				
				<!-- 自己消息（右侧） -->
				<template v-else>
					<view class="message-detail-page__bubble message-detail-page__bubble--self">
						<text class="message-detail-page__bubble-text">{{ message.content }}</text>
						<text class="message-detail-page__bubble-time">{{ formatTime(message.timestamp) }}</text>
					</view>
					<view class="message-detail-page__avatar message-detail-page__avatar--self">
						<text class="message-detail-page__avatar-text">{{ getAvatarText(currentUserName) }}</text>
					</view>
				</template>
			</view>
		</scroll-view>
		
		<!-- 输入框 -->
		<view class="message-detail-page__input-area">
			<input 
				class="message-detail-page__input" 
				v-model="inputMessage" 
				placeholder="输入消息..." 
				@confirm="handleSendMessage" 
				:disabled="sending" />
			<button 
				class="message-detail-page__send-btn" 
				:class="{ 'message-detail-page__send-btn--disabled': !inputMessage.trim() || sending }"
				@click="handleSendMessage"
				:disabled="!inputMessage.trim() || sending">
				{{ sending ? '发送中...' : '发送' }}
			</button>
		</view>
	</view>
</template>

<script>
import messageManager from "@/utils/message"

export default {
	data() {
		return {
			sessionKey: '', // 会话标识（对方ID）
			chatPartnerId: '', // 对方ID
			chatPartnerName: '', // 对方姓名
			currentUserId: '', // 当前用户ID
			currentUserName: '', // 当前用户名
			inputMessage: '', // 输入的消息
			messageList: [], // 消息列表
			scrollTop: 0,
			sending: false // 发送中状态
		}
	},
	computed: {
		// 判断是否是护理专家
		isExpert() {
			const roles = this.$store.state.user.roles || []
			return roles.some(role => {
				if (!role || typeof role !== 'string') return false
				const lowerRole = role.toLowerCase()
				return lowerRole === 'expert' || lowerRole.includes('expert')
			})
		}
	},
	onLoad(options) {
		this.initPage(options)
		this.loadMessages()
		uni.$on('message-updated', this.handleMessageUpdated)
	},
	onUnload() {
		uni.$off('message-updated', this.handleMessageUpdated)
		uni.$emit('message-updated')
	},
	methods: {
		// 初始化页面
		initPage(options) {
			this.sessionKey = options.sessionKey || ''
			this.chatPartnerId = options.sessionKey || ''
			this.chatPartnerName = decodeURIComponent(options.nurseName || options.groupName || '未知用户')
			this.currentUserId = this.$store.state.user.id || ''
			this.currentUserName = this.$store.state.user.name || '我'
		},
		
		// 加载消息
		loadMessages() {
			// 先保存到局部变量，确保在回调中能正确访问
			const currentUserId = this.currentUserId
			const chatPartnerId = this.chatPartnerId
			
			// 防御性检查
			if (!currentUserId || !chatPartnerId) {
				console.warn('用户ID或会话ID不存在，无法加载消息', {
					currentUserId,
					chatPartnerId
				})
				this.messageList = []
				return
			}
			
			const allMessages = uni.getStorageSync('all_messages') || []
			
			// 筛选当前会话的消息：双方互发的消息
			const sessionMessages = allMessages.filter(msg => {
				const isFromMe = msg.senderId == currentUserId && msg.receiverId == chatPartnerId
				const isToMe = msg.senderId == chatPartnerId && msg.receiverId == currentUserId
				return isFromMe || isToMe
			})
			
			// 按时间排序并标记是否是自己发送的
			this.messageList = sessionMessages
				.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp))
				.map(msg => ({
					...msg,
					isSelf: msg.senderId === currentUserId
				}))
			
			// 标记消息为已读
			this.markMessagesAsRead()
			
			// 滚动到底部
			this.$nextTick(() => {
				this.scrollToBottom()
			})
		},
		
		// 标记消息为已读
		markMessagesAsRead() {
			const currentUserId = this.currentUserId
			const chatPartnerId = this.chatPartnerId
			
			if (!currentUserId || !chatPartnerId) {
				return
			}
			
			const allMessages = uni.getStorageSync('all_messages') || []
			let updated = false
			
			allMessages.forEach(msg => {
				// 标记对方发送给我的未读消息为已读
				if (!msg.isRead && msg.senderId == chatPartnerId && msg.receiverId == currentUserId) {
					msg.isRead = true
					updated = true
				}
			})
			
			if (updated) {
				uni.setStorageSync('all_messages', allMessages)
			}
		},
		
		// 发送消息
		async handleSendMessage() {
			const content = this.inputMessage.trim()
			if (!content || this.sending) return
			
			this.sending = true
			
			try {
				const message = {
					id: Date.now().toString(),
					senderId: this.currentUserId,
					senderName: this.currentUserName,
					senderType: this.isExpert ? 'expert' : 'nurse',
					receiverId: this.chatPartnerId,
					receiverName: this.chatPartnerName,
					receiverType: this.isExpert ? 'nurse' : 'expert',
					content: content,
					timestamp: new Date().getTime(),
					isRead: false
				}
				
				// 立即添加到消息列表
				this.messageList.push({
					...message,
					isSelf: true
				})
				
				// 保存到本地存储
				const allMessages = uni.getStorageSync('all_messages') || []
				allMessages.push(message)
				uni.setStorageSync('all_messages', allMessages)
				
				// 清空输入框
				this.inputMessage = ''
				
				// 滚动到底部
				this.$nextTick(() => {
					this.scrollToBottom()
				})
				
				// 触发页面更新
				uni.$emit('message-updated')
				
				// 发送到服务器
				try {
					const serverMessage = await messageManager.sendMessageToServer(message)
					if (serverMessage.id && serverMessage.id !== message.id) {
						const allMessages = uni.getStorageSync('all_messages') || []
						const index = allMessages.findIndex(msg => msg.id == message.id)
						if (index !== -1) {
							allMessages[index] = { ...allMessages[index], ...serverMessage }
							uni.setStorageSync('all_messages', allMessages)
						}
					}
				} catch (error) {
					console.error('发送消息到服务器失败:', error)
					uni.showToast({
						title: '发送失败，请重试',
						icon: 'none'
					})
				}
			} finally {
				this.sending = false
			}
		},
		
		// 格式化时间
		formatTime(timestamp) {
			if (!timestamp) return ''
			const date = new Date(timestamp)
			const hours = date.getHours().toString().padStart(2, '0')
			const minutes = date.getMinutes().toString().padStart(2, '0')
			return `${hours}:${minutes}`
		},
		
		// 获取头像文字
		getAvatarText(name) {
			if (!name) return '?'
			return name.charAt(0).toUpperCase()
		},
		
		// 滚动到底部
		scrollToBottom() {
			this.scrollTop = 99999
		},
		
		// 滚动到底部事件
		handleScrollToBottom() {
			// 可以在这里加载历史消息
		},
		
		// 消息更新事件处理
		handleMessageUpdated() {
			this.loadMessages()
		}
	}
}
</script>

<style lang="scss" scoped>
.message-detail-page {
	display: flex;
	flex-direction: column;
	height: 100vh;
	background-color: #ededed;
	
	&__header {
		background-color: #ffffff;
		padding: 30rpx;
		text-align: center;
		border-bottom: 1rpx solid #e8ecf0;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	}
	
	&__header-name {
		font-size: 36rpx;
		font-weight: bold;
		color: #333333;
	}
	
	&__messages {
		flex: 1;
		padding: 20rpx;
		background-color: #ededed;
	}
	
	&__item {
		display: flex;
		align-items: flex-start;
		margin-bottom: 30rpx;
		
		&--self {
			justify-content: flex-end;
		}
	}
	
	&__avatar {
		width: 80rpx;
		height: 80rpx;
		background: linear-gradient(135deg, #4a90e2 0%, #67c23a 100%);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 20rpx;
		flex-shrink: 0;
		
		&--self {
			margin-right: 0;
			margin-left: 20rpx;
			background: linear-gradient(135deg, #67c23a 0%, #4a90e2 100%);
		}
	}
	
	&__avatar-text {
		font-size: 32rpx;
		color: #ffffff;
		font-weight: bold;
	}
	
	&__bubble {
		max-width: 500rpx;
		padding: 20rpx 24rpx;
		border-radius: 12rpx;
		position: relative;
		
		&--other {
			background-color: #ffffff;
			border-top-left-radius: 4rpx;
		}
		
		&--self {
			background-color: #95ec69;
			border-top-right-radius: 4rpx;
		}
	}
	
	&__bubble-name {
		font-size: 22rpx;
		color: #999999;
		display: block;
		margin-bottom: 8rpx;
	}
	
	&__bubble-text {
		font-size: 30rpx;
		color: #333333;
		line-height: 1.6;
		display: block;
		word-break: break-all;
	}
	
	&__bubble--self &__bubble-text {
		color: #333333;
	}
	
	&__bubble-time {
		font-size: 22rpx;
		color: #999999;
		display: block;
		text-align: right;
		margin-top: 8rpx;
	}
	
	&__bubble--self &__bubble-time {
		color: #666666;
	}
	
	&__input-area {
		background-color: #ffffff;
		padding: 20rpx;
		display: flex;
		align-items: center;
		gap: 20rpx;
		border-top: 1rpx solid #e0e0e0;
	}
	
	&__input {
		flex: 1;
		height: 80rpx;
		background-color: #f5f5f5;
		border-radius: 40rpx;
		padding: 0 30rpx;
		font-size: 28rpx;
		color: #333333;
	}
	
	&__send-btn {
		background-color: #4a90e2;
		color: #ffffff;
		border: none;
		border-radius: 40rpx;
		padding: 0 40rpx;
		height: 80rpx;
		line-height: 80rpx;
		font-size: 28rpx;
		font-weight: 500;
		flex-shrink: 0;
		
		&:active {
			background-color: #3a7bc8;
		}
		
		&--disabled {
			background-color: #cccccc;
			color: #999999;
		}
	}
}
</style>

